package com.zhq.base;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhq.bean.PageBean;
import com.zhq.okhttp.RxApiManager;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.CompositeDisposable;


public abstract class BasePresenter<T> {

    /**
     * View的弱引用
     */
    protected T mViewRef;
    protected Context mContext;
    public static final int REQUEST_Gallery_CODE = 1000;
    protected CompositeDisposable disposables = new CompositeDisposable();
    private PageBean<?> pageBean = new PageBean<>();

    public BasePresenter(Context mContext) {
        this.mContext = mContext;
        //DbManager.getInstance().onInit(mContext);
    }

    public PageBean<?> getPageBean() {
        return pageBean;
    }

    public void attach(T mView) {
        this.mViewRef = mView;

    }

    public void detachView() {
        if (mViewRef != null) {
            mViewRef = null;
        }
        cancelAllRequest();
        RxApiManager.get().clearAllListener();
        //DbManager.getInstance().closeDB();
    }

    /**
     * View是否绑定
     *
     * @return
     */
    public boolean isViewAttached() {
        return mViewRef != null;
    }

    /**
     * 得到VIew
     *
     * @return
     */
    protected T getView() {
        return mViewRef;
    }

    public Context getmContext() {
        return mContext;
    }

    /***
     *
     * @return
     */
    public CompositeDisposable getDisposables() {
        return disposables;
    }

    /***
     * 获取数据源
     * @param result
     * @return
     */
    public Map<String,Object> getData(String result) {
        JSONObject jsonObject = JSON.parseObject(result);
        String data = jsonObject.getString("rows");
        Map<String,Object> map=new HashMap<>();
        map.put("data",data);
        map.put("totalCount",jsonObject.getInteger("total"));
        return map;
    }


    /**
     * 页面销毁时取消所有网络请求
     */
    private void cancelAllRequest() {
        disposables.clear();
    }
}
